<script setup lang="ts">
  import { reactive, ref, useTemplateRef } from 'vue'

  import CudTable, { type TQTableColumns, type TRequestParam } from '@/components/CudTable.vue'
  import {
    getTenantPageList,
    getHousePageList,
    type IEditTenantParam,
    type ITenantQueryParams,
    editTenant
  } from '@/api'

  import { useQuasar, QUploader, uid } from 'quasar'
  import { getUserInfo, isRequestSuccess } from '@/utils'

  const $q = useQuasar()
  const filter = ref('')
  const tableRef = useTemplateRef('table')
  const classes = 'max-w-[160px] break-all'

  const columns: TQTableColumns = [
    { name: 'tenantId', label: '租客ID', field: 'tenantId', align: 'left', classes },
    { name: 'company', label: '公司', field: 'company', align: 'left', classes },
    { name: 'name', label: '姓名', field: 'name', align: 'left', classes },
    { name: 'idNumber', label: '身份证号', field: 'idNumber', align: 'left', classes },
    { name: 'phoneNumber', label: '电话', field: 'phoneNumber', align: 'left', classes },
    { name: 'houseNumber', label: '房号', field: 'houseNumber', align: 'left', classes },
    { name: 'rent', label: '租金', field: 'rent', align: 'left', classes },
    { name: 'leaseStartDate', label: '起租日期', field: 'leaseStartDate', align: 'left', classes },
    { name: 'leaseEndDate', label: '退租日期', field: 'leaseEndDate', align: 'left', classes },
    { name: 'contract', label: '合同', field: 'contract', align: 'left', classes },
    { name: 'action', label: '操作', field: 'action', align: 'left', classes }
  ]
  function request(context: TRequestParam) {
    const { page, rowsPerPage } = context.pagination
    const params: ITenantQueryParams = { pageNum: page, pageSize: rowsPerPage }
    if (filter.value) {
      params.houseNumber = filter.value
    }
    return getTenantPageList(params)
  }

  function onKeyInput(event: KeyboardEvent) {
    if (event.key.toLowerCase() === 'enter') {
      // 13 为回车键
      onSearch()
    }
  }
  function onSearch() {
    if (tableRef.value) {
      tableRef.value.refreshUserTable(1)
    }
  }

  // add edit dialog
  const rShowDialog = ref(false)
  const editRow: IEditTenantParam = {
    tenantId: -1,
    name: '',
    idNumber: '',
    phoneNumber: '',
    houseNumber: '',
    address: '',
    rent: 0,
    leaseStartDate: '',
    leaseEndDate: '',
    contract: ''
  }
  const rHouseNumberOptions = ref<string[]>([])
  const pEditRow = reactive<IEditTenantParam>(Object.assign({}, editRow))
  function onShowDialog(row?: any) {
    const keys = Object.keys(editRow) as (keyof IEditTenantParam)[]
    keys.forEach(key => {
      pEditRow[key] = row[key]
    })
    rShowDialog.value = true
  }
  async function onDialogSubmit() {
    const res = await editTenant({ ...pEditRow })
    if (isRequestSuccess(res)) {
      $q.notify({
        type: 'positive',
        message: '提交成功'
      })
      onSearch()
    } else {
      $q.notify({
        color: 'red-5',
        textColor: 'white',
        icon: 'warning',
        message: '提交失败'
      })
    }
    onCancel()
  }
  function onCancel() {
    rShowDialog.value = false
  }
  // upload
  const rUid = ref(uid())
  const rUploaderContract = useTemplateRef<QUploader>('q_uploader_contract')
  const oUser = getUserInfo() as IUser
  const headers = [{ name: 'Authorization', value: `Bearer ${oUser.accessToken}` }]
  function onUploadedContract(info: any) {
    rUid.value = uid()
    try {
      const res = JSON.parse(info.xhr.response)
      if (res.code == 200 && res.data && res.data.url) {
        pEditRow.contract = res.data.url
      }
    } catch (e) {
      console.log(e, '上传内容解析错误')
    }
  }
  function onContracUpload(event: Event) {
    if (rUploaderContract.value) {
      rUploaderContract.value.pickFiles(event)
    }
  }

  function onFailed(info: any) {
    const fileNames = info.files.map((file: IOption) => file.name).join(',')
    rUid.value = uid()
    $q.notify({
      color: 'red-5',
      textColor: 'white',
      icon: 'warning',
      message: `${fileNames}上传失败，请重试`
    })
  }

  // init
  function init() {
    let records = new Set([])
    getHousePageList({ pageNum: 1, pageSize: 100000 })
      .then(res => {
        if (isRequestSuccess(res)) {
          records = new Set(res.data.data.records.map((r: any) => r.houseNumber) || [])
          rHouseNumberOptions.value = Array.from(records)
        }
      })
      .catch(error => {
        console.log(error)
      })
  }
  init()
</script>

<template>
  <q-page class="bg-[#FAFCFF] p-5">
    <CudTable
      ref="table"
      class="bg-white p-5"
      title="租客管理"
      row-key="tenantId"
      :columns="columns"
      :request="request">
      <template v-slot:top-right>
        <q-input outlined dense @keydown="onKeyInput" v-model="filter" placeholder="请输入房号查询">
          <template v-slot:append>
            <q-icon name="search" @click="onSearch" />
          </template>
        </q-input>
      </template>
      <template v-slot:body-cell-action="{ row }">
        <td class="text-center w-[120px]">
          <span @click="onShowDialog(row)" class="text-[#2265D4] cursor-pointer">编辑</span>
          <!--          <span @click="onRemove(row)" class="text-[#EB4242] cursor-pointer ml-2">删除</span>-->
        </td>
      </template>
    </CudTable>
    <q-dialog v-model="rShowDialog" class="ud-dialog">
      <q-card class="!max-w-none w-[80%] flex flex-col no-wrap">
        <q-form @submit="onDialogSubmit" class="flex-1 flex flex-col">
          <div class="flex-1">
            <q-card-section class="text-h6 text-[#409EFD] relative">
              <div class="text-h6 text-[#409EFD] relative">
                <b class="v-blue-line"></b>
                租客信息
              </div>
            </q-card-section>
            <q-card-section horizontal class="px-8">
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">租客姓名：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.name"
                  outlined
                  dense
                  placeholder="请输入租客姓名"></q-input>
              </div>
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">联系电话：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.phoneNumber"
                  outlined
                  dense
                  placeholder="请输入联系电话"></q-input>
              </div>
            </q-card-section>
            <q-card-section horizontal class="px-8 mt-8">
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">身份证：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.idNumber"
                  outlined
                  dense
                  placeholder="请输入身份证号"></q-input>
              </div>
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">租客ID：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.tenantId"
                  disable
                  outlined
                  filled
                  dense
                  placeholder="请输入租客ID"></q-input>
              </div>
            </q-card-section>

            <q-card-section class="text-h6 text-[#409EFD] relative">
              <div class="text-h6 text-[#409EFD] relative">
                <b class="v-blue-line"></b>
                房源信息
              </div>
            </q-card-section>
            <q-card-section horizontal class="px-8">
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">房号：</div>
                <q-select
                  class="flex-1 pb-0"
                  outlined
                  hide-dropdown-icon
                  fill-input
                  placeholder="请输入房号"
                  v-model="pEditRow.houseNumber"
                  :options="rHouseNumberOptions"
                  dense
                  options-dense>
                  <template v-slot:append>
                    <q-btn class="house-number-btn" color="primary" label="选择" />
                  </template>
                </q-select>
              </div>
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">地址：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.address"
                  disable
                  dense
                  outlined
                  filled
                  placeholder="请输入地址"></q-input>
              </div>
            </q-card-section>

            <q-card-section class="text-h6 text-[#409EFD] relative">
              <div class="text-h6 text-[#409EFD] relative">
                <b class="v-blue-line"></b>
                租赁合同信息
              </div>
            </q-card-section>
            <q-card-section horizontal class="px-8">
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">合同上传：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.contract"
                  outlined
                  dense
                  placeholder="请输入合同上传">
                  <template v-slot:append>
                    <q-uploader
                      :key="rUid"
                      class="ud-q-uploader ud-q-uploader-excel"
                      auto-upload
                      url="http://47.115.213.19/house/upload"
                      field-name="file"
                      :headers="headers"
                      @failed="onFailed"
                      @uploaded="onUploadedContract"
                      ref="q_uploader_contract" />
                    <q-btn
                      @click="onContracUpload"
                      class="house-number-btn"
                      color="primary"
                      label="选择" />
                  </template>
                </q-input>
              </div>
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">租金：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.rent"
                  outlined
                  dense
                  placeholder="请输入租金"></q-input>
              </div>
            </q-card-section>
            <q-card-section horizontal class="px-8 mt-8">
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">起租日期：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.leaseStartDate"
                  outlined
                  dense
                  placeholder="请输入起租日期">
                  <template v-slot:append>
                    <q-btn class="house-number-btn" color="primary" label="选择" />
                    <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                      <q-date
                        v-model="pEditRow.leaseStartDate"
                        mask="YYYY-MM-DDTHH:mm:ss"
                        emit-immediately
                        minimal>
                        <div class="row items-center justify-end">
                          <q-icon name="bi-clock" color="primary" class="cursor-pointer">
                            <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                              <q-time
                                v-model="pEditRow.leaseStartDate"
                                mask="YYYY-MM-DDTHH:mm:ss"
                                format24h
                                with-seconds>
                                <div class="row items-center justify-end">
                                  <q-btn v-close-popup label="关闭" color="primary" flat></q-btn>
                                </div>
                              </q-time>
                            </q-popup-proxy>
                          </q-icon>
                          <q-btn v-close-popup label="确定" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </template>
                </q-input>
              </div>
              <div class="flex-1 flex items-center">
                <div class="w-[160px] text-right text-lg text-[#333]">退租日期：</div>
                <q-input
                  class="flex-1 pb-0"
                  v-model="pEditRow.leaseEndDate"
                  outlined
                  dense
                  placeholder="请输入退租日期">
                  <template v-slot:append>
                    <q-btn class="house-number-btn" color="primary" label="选择" />
                    <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                      <q-date
                        v-model="pEditRow.leaseEndDate"
                        mask="YYYY-MM-DDTHH:mm:ss"
                        emit-immediately
                        minimal>
                        <div class="row items-center justify-end">
                          <q-icon name="bi-clock" color="primary" class="cursor-pointer">
                            <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                              <q-time
                                v-model="pEditRow.leaseEndDate"
                                mask="YYYY-MM-DDTHH:mm:ss"
                                format24h
                                with-seconds>
                                <div class="row items-center justify-end">
                                  <q-btn v-close-popup label="关闭" color="primary" flat></q-btn>
                                </div>
                              </q-time>
                            </q-popup-proxy>
                          </q-icon>
                          <q-btn v-close-popup label="确定" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </template>
                </q-input>
              </div>
            </q-card-section>
          </div>

          <div class="flex flex-center gap-7 pb-5 mt-8">
            <q-btn
              color="blue-6"
              padding="10px 40px"
              text-color="white"
              label="确认"
              type="submit" />
            <q-btn outline padding="10px 40px" @click="onCancel" color="light-blue" label="取消" />
          </div>
        </q-form>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<style scoped>
  .house-number-btn {
    position: relative;
    right: -12px;
    padding: 8px 20px;
    top: 0;
    z-index: 10;
  }
</style>
